const vscode = require("vscode");
const fs = require('fs');
const path = require('path');
const MapWebviewProvider = require('./MapWebviewProvider');
const {
    SetConfigList,
    GetConfigList,
    War3Helper,
} = require('./lua');

/**
 * 插件被激活时触发，所有代码总入口
 * @param {vscode.ExtensionContext} context 插件上下文
 */
module.exports = async function (context) {
    const webviewProvider = new MapWebviewProvider(context);
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider('war3helper.info', webviewProvider)
    );
    context.subscriptions.push(vscode.commands.registerCommand('war3helper.updateConfig', async () => {
        await webviewProvider.updateConfig()
    }));
    context.subscriptions.push(vscode.commands.registerCommand('war3helper.update', async () => {
        await webviewProvider.update()
    }));
    context.subscriptions.push(vscode.commands.registerCommand('war3helper.CLuaPackagePath', async () => {
        const input = await vscode.window.showInputBox({
            prompt: `请输入CLuaPackagePath`,
            placeHolder: 'CLuaPackagePath'
        });

        if (input !== undefined) {
            SetConfigList('CLuaPackagePath', String(input))
        }
    }));
    context.subscriptions.push(vscode.commands.registerCommand('war3helper.UnitXlsxPath', async () => {
        const input = await vscode.window.showInputBox({
            prompt: `请输入单位物编表格路径`,
            placeHolder: '单位物编表格路径'
        });

        if (input !== undefined) {
            SetConfigList('单位物编表格', String(input))
            if (vscode.workspace.getConfiguration().get("war3helper.OutUnitXlsx")) {
                webviewProvider.statusBarItem5.show();
            } else {
                vscode.window.showInformationMessage('请打开单位物编表格导出功能设置');
            }
            if (vscode.workspace.getConfiguration().get("war3helper.SaveUnitXlsx")) {
                webviewProvider.statusBarItem6.show();
            }
            else {
                vscode.window.showInformationMessage('请打开单位物编表格保存功能设置');
            }
        }
    }));
    context.subscriptions.push(vscode.commands.registerCommand('war3helper.AddPluginScript', async (type) => {
        let input = await vscode.window.showInputBox({
            prompt: `请输入脚本备注名`,
            placeHolder: '脚本备注名'
        });
        if (input !== undefined) {
            let Scripts = (await GetConfigList('PluginScripts')) ?? []

            let Has = false;
            for (let i = 0; i < Scripts.length; i++) {
                var script = Scripts[i];
                if (script['name'] == String(input)) {
                    Has = true;
                }
            }

            Scripts.push({
                name: String(input),
                type: type,
                enable: true
            });

            SetConfigList("PluginScripts", Scripts)
            vscode.window.showInformationMessage(`创建插件脚本:${type}`);

            if (Has) {
                return;
            }
            const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;
            if (!await fs.existsSync(path.join(workspaceFolder, ".tools"))) {
                await fs.mkdirSync(path.join(workspaceFolder, ".tools"), { recursive: true });
            }
            let text = "";
            switch (type) {
                case '运行地图前执行':
                    text = `
---@class Csharp.War3MapPluginBuilder.${String(input)} : Csharp.War3MapPluginBuilder
local builder = {}

--- 初始化地图时回调
function builder:InitWar3Map()

end

--- 打包文件时的回调
---@param data Csharp.BuilderFile
function builder:OnBuilderFile(data)

end

--- 打包文件完成的回调
function builder:OnBuilderFileFinish()

end

return builder
`
                    break;
                case '生成发布版前执行':
                    text = `
---@class Csharp.War3MapPluginBuilder.${String(input)} : Csharp.War3MapPluginBuilder
local builder = {}

--- 初始化地图时回调
function builder:InitWar3Map()

end

--- 打包文件时的回调
---@param data Csharp.BuilderFile
function builder:OnBuilderFile(data)

end

--- 打包文件完成的回调
function builder:OnBuilderFileFinish()

end

--- 打包Luac文件时的回调
---@param data Csharp.BuilderLuacFile
function builder:OnBuilderLuacFile(data)

end

--- 云脚本进入压缩包事件
---@param data Csharp.BuilderCloudLuaFile
function builder:OnBuilderCloudLuaFile(data)

end

return builder
                    `
                    break;
                case '生成发布版后执行':
                    break;
            }
            await fs.writeFileSync(path.join(workspaceFolder, ".tools", String(input) + ".lua"), text.trim(), "utf-8")
            vscode.commands.executeCommand("vscode.open", vscode.Uri.file(path.join(workspaceFolder, ".tools", String(input) + ".lua")));
        }
    }));

    context.subscriptions.push(vscode.commands.registerCommand('war3helper.RemovePluginScript', async (msg) => {
        let list = msg.split(':');
        let type = list[0];
        let name = list[1];
        // 删除对应的 .lua 文件
        const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;
        const scriptPath = path.join(workspaceFolder, ".tools", name + ".lua");
        if (await fs.existsSync(scriptPath)) {
            let Scripts = (await GetConfigList('PluginScripts')) ?? []
            var script = Scripts.find(item => item.name == name && item.type != type);
            if (!script) {
                await fs.unlinkSync(scriptPath); // 删除文件   
            } else {
                Scripts = Scripts.filter(item => !(item.name == name && item.type == type));
                await SetConfigList('PluginScripts', Scripts);
            }
            War3Helper.info(`✅ 已删除插件脚本: ${scriptPath}`);
        } else {
            War3Helper.info(`❌ 未找到插件脚本: ${scriptPath}`);
        }
        War3Helper.hide();
        War3Helper.show();
    }));

    context.subscriptions.push(vscode.commands.registerCommand('war3helper.EnablePluginScript', async (msg) => {
        let list = msg.split(':');
        let type = list[0];
        let name = list[1];
        let Scripts = (await GetConfigList('PluginScripts')) ?? []
        var script = Scripts.find(item => item.name == name && item.type == type);

        if (script != null) {
            if (script['enable'] == true) {
                War3Helper.info(`✅ 禁用插件脚本: {type:${type} name:${name}}`);
                script['enable'] = false;
            } else {
                War3Helper.info(`✅ 启用插件脚本: {type:${type} name:${name}}`);
                script['enable'] = true;
            }
            War3Helper.hide()
            War3Helper.show()
        }
        await SetConfigList('PluginScripts', Scripts);
    }));
    context.subscriptions.push(vscode.commands.registerCommand('war3helper.OpenPluginScript', async (name) => {
        const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;
        vscode.commands.executeCommand("vscode.open", vscode.Uri.file(path.join(workspaceFolder, ".tools", name + ".lua")));
    }));
}